<?php

namespace App\Http\Controllers\Api\newWork;

use App\Library\WeChat;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class WorkListController extends CommonController
{
    private $workReplyTableName = "new_work_reply";
    private $workListTableName = "new_work_list";
    private $workChangeTableName = "new_work_change";
    private $catTableName = "new_work_cat";
    private $adminUserTableName = "admin_users";
    private $typeTableName = "new_work_type";
    private $memberTableName = "member";
    private $settingTableName = "new_work_setting";
    private $replyField = [
    "list_id" => "require", "feedback" => "require", "picture" => 'require',
    "annex" => "require"
]; // 填入数据库需要存储的表字段;
    private $replyFieldMsg = [
        "list_id" => "所属工单ID", "user_id" => "回复人ID", "feedback" => "反馈内容", "picture" => '图片列表',
        "annex" => "附件列表"
    ];
    public function __construct()
    {
        parent::__construct();
    }

    // 获取工单反馈列表
    public function getWorkOrderList(){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $param = request()->post();
        $pageNo = isset($param["pageNo"]) ? $param["pageNo"] : 1;
        $pageSize = isset($param["pageSize"]) ? $param["pageSize"] : 10;
        $type = isset($param["type"]) ? $param["type"] : '1';
        if(!in_array($type, ['1','2','3'])){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = 'type参数错误，1待签收 2处理中 3已解决';
            return response()->json($this->returnData);
        }
        $data = DB::table($this->workListTableName . " as l")
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','t.cat_id')
            ->where("l.receive_id", $this->user["id"])
            ->where("l.status", $type)
            ->where("l.mall_id", request()->mallData["id"])
            ->select("l.id", "l.feedback", "l.status", "l.tag", "l.create_time", "c.name as catName", "t.name as typeName")
            ->skip(($pageNo - 1) * $pageSize)->take($pageSize)
            ->orderBy("l.create_time", "desc")
            ->get();
        $data = $this->transferFields(json_decode(json_encode($data), true));
        foreach ($data as &$item) {
            $item["feedback"] = json_decode($item["feedback"], true);
        }
        $this->returnData['data'] = $data;
        return response()->json($this->returnData);
    }

    public function getWorkOrderChangeList(){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $param = request()->post();
        $pageNo = isset($param["pageNo"]) ? $param["pageNo"] : 1;
        $pageSize = isset($param["pageSize"]) ? $param["pageSize"] : 10;
        $db = DB::table($this->workChangeTableName . " as c")
            ->leftJoin("{$this->workListTableName} as l",'c.list_id','=','l.id')
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as cat",'cat.id','=','t.cat_id')
            ->where("c.present_id", $this->user["id"])
            ->where("c.mall_id", request()->mallData["id"])
            ->select("c.id as changeId", "l.id", "c.remark", "c.status as changeStatus", "l.status", "c.create_time", "cat.name as catName", "t.name as typeName");
        if(isset($param["status"])){
            if($param["status"] == "0")
                $db->where("c.status", "1");
            if($param["status"] == "1")
                $db->whereIn("c.status", ["2","3"]);
        }
        $data = $db->skip(($pageNo - 1) * $pageSize)->take($pageSize)->orderBy("c.create_time", "desc")->get();
        $data = $this->transferFields(json_decode(json_encode($data), true));
        $this->returnData['data'] = $data;
        return response()->json($this->returnData);
    }

    // 获取工单详情
    public function getWorkOrderInfo(){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $param = request()->post();
        if(empty($param["id"])){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单ID不能为空';
            return response()->json($this->returnData);
        }
        $data = DB::table($this->workListTableName . " as l")
            ->leftJoin("{$this->memberTableName} as m",'l.user_id','=','m.id')
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','t.cat_id')
            ->select("l.*", "m.name as userName", "m.mobile as userMobile", "c.name as catName", "t.name as typeName")
            ->where("l.id", $param["id"])->where("l.mall_id", request()->mallData["id"])->first();
        $data = $this->transferFields(json_decode(json_encode($data),true));
        if(empty($data)){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单不存在';
            return response()->json($this->returnData);
        }
        $data["feedback"] = json_decode($data["feedback"], true);
        // 反馈记录
        $replyData = DB::table($this->workReplyTableName)
            ->select("feedback", "picture", "annex", "create_time", "user_id", "submit_id")
            ->orderBy("create_time", "desc")
            ->where("list_id", $param["id"])->get();
        $replyData = $this->transferFields(json_decode(json_encode($replyData),true));
        foreach ($replyData as &$item){
            $item["annex"] = @json_decode($item["annex"]);
            $item["picture"] = explode(",", $item["picture"]);
            if(!empty($item["userId"])){
                if(!isset($temp["admin"][$item["userId"]])){
                    $tmp = DB::table($this->adminUserTableName)->where("id", $item["userId"])->select("name")->first();
                    $temp["admin"][$item["userId"]] = !empty($tmp->name) ? $tmp->name : "";
                }
                $item["isManage"] = "1";
                $item["name"] = $temp["admin"][$item["userId"]];
            }elseif(!empty($item["submitId"])){
                if(!isset($temp["member"][$item["submitId"]])){
                    $tmp = DB::table($this->memberTableName)->where("id", $item["submitId"])->select("name")->first();
                    $temp["member"][$item["submitId"]] = !empty($tmp->name) ? $tmp->name : "";
                }
                $item["isManage"] = "0";
                $item["name"] = $temp["member"][$item["submitId"]];
            }
        }
        $data["replyData"] = $replyData;
        if($data["isTransfer"] == "1"){ // 已转单，查转单详情
            $changeData = DB::table($this->workChangeTableName)
                ->where("list_id", $param["id"])->where("present_id", $this->user["id"])
                ->select("remark", "reason", "status")->first();
            $data["changeData"] = $this->transferFields(json_decode(json_encode($changeData),true));
        }
        $this->returnData['data'] = $data;
        return response()->json($this->returnData);
    }

    // 工单签收
    public function workOrderSignIn(){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $param = request()->post();
        if(empty($param["id"])){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单ID不能为空';
            return response()->json($this->returnData);
        }
        if(DB::table($this->workListTableName)->where("id", $param["id"])->update(["status" => '2', "receive_time" => date("Y-m-d H:i:s")])){
            $this->returnData['msg'] = '签收成功';
        }else{
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '签收失败';
        }
        return response()->json($this->returnData);
    }

    // 申请转单
    public function transferWorkOrder(){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $param = request()->post();
        if(empty($param["id"])){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单ID不能为空';
            return response()->json($this->returnData);
        }
        if(empty($param["remark"])){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '转单备注不能为空';
            return response()->json($this->returnData);
        }
        $listData = DB::table($this->workListTableName)->where("id", $param["id"])->select("receive_id", "status")->first();
        if(empty($listData)){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单不存在';
            return response()->json($this->returnData);
        }
        if($listData->status == '3'){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单已解决了';
            return response()->json($this->returnData);
        }
        if(DB::table($this->workChangeTableName)->where("list_id", $param["id"])->where("status", "1")->count()){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单已转单';
            return response()->json($this->returnData);
        }
        $res = DB::table($this->workChangeTableName)->insert([
            "list_id" => $param["id"], "remark" => $param["remark"], "status" => 1, "present_id" => $listData->receive_id,
            "new_id" => isset($param["userId"]) ? $param["userId"] : NULL, "create_time" => date("Y-m-d H:i:s"),
            "mall_id" => request()->mallData["id"]
        ]);
        if($res){
            DB::table($this->workListTableName)->where("id", $param["id"])->update(["is_transfer" => '1']);
            $this->returnData['msg'] = '转单申请成功';
        }else{
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '转单申请失败';
        }
        return response()->json($this->returnData);
    }

    // 保存工单反馈信息
    public function saveFeedBack(){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $params = request()->post();
        $data["create_time"] = date("Y-m-d H:i:s");
        $data["user_id"] = $this->user["id"];
        foreach ($this->replyField as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if($v === 'require' && !isset($params[$ks])){
                $this->returnData['status'] = 1;
                $this->returnData['msg'] = "{$this->replyFieldMsg[$k]}不能为空";
                return response()->json($this->returnData);
            }
            $data[$k] = isset($params[$ks]) ? trim($params[$ks]) : $v;
        }
        $listData = DB::table($this->workListTableName . " as l")
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','t.cat_id')
            ->select("l.user_id", "l.status", "c.name as catName", "t.name as typeName")
            ->where("l.id", $params["listId"])->first();
        if(empty($listData)){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单不存在';
            return response()->json($this->returnData);
        }
        if($listData->status == '3'){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单已解决了';
            return response()->json($this->returnData);
        }
        $res = DB::table($this->workReplyTableName)->insert($data);
        if(!$res){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '提交失败';
            return response()->json($this->returnData);
        }
        if($listData->status == '1') {
            DB::table($this->workListTableName)->where("id", $params["listId"])->update(["status" => '2']);
        }
        $this->returnData['msg'] = '提交成功';
        $setting = DB::table($this->settingTableName)->where("mall_id", request()->mallData["id"])->select("wx_reply_template", "sms_reply_template")->first();
        $memberData = DB::table($this->memberTableName)->where("id", $listData->user_id)->select("mobile", "openid")->first();
        if(!empty($memberData->mobile) && $setting->sms_reply_template){ // 发送短信
            $this->sendSms($memberData->mobile, $setting->sms_reply_template, [date("Y-m-d H:i:s")]); // 发送短信
        }
        if(!empty($setting->wx_reply_template)){
            $res = WeChat::sendTemplateMsg($memberData->openid, $setting->wx_reply_template, [
                "number1" => ["value" => $params["listId"]], "phrase2" => ["value" => $listData->catName], "phrase3" => ["value" => $listData->typeName]
            ], $msg);
            if(!$res){
                $this->returnData['msg'] .= "，{$msg}";
            }
        }
        return response()->json($this->returnData);
    }

    // 工单结单
    public function workOrderFinish(){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $params = request()->post();
        if(empty($param["id"])){
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '工单ID不能为空';
            return response()->json($this->returnData);
        }
        if(DB::table($this->workListTableName)->where("id", $params["id"])->update(["status" => '3'])){
            $this->returnData['msg'] = '结单成功';
        }else{
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '结单失败';
        }
        return response()->json($this->returnData);
    }
}
